package evolution;

import ca.swank.hardquor.*;
import ca.swank.hq.ai.CachingSmartBoard;
import ca.swank.hq.ai.hqSimpleAIGame;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

/**
 * 
 * @author Alon Segal
 * 
 */
public class RandomAIGame extends hqSimpleAIGame {

	public RandomAIGame(hardquorGameClient gameClient, int me, String userName) {
		super(gameClient, me, userName);
	}

	/**
	 * notification that a move required by the current player.
	 * 
	 * The player initially speaks a comment to the board, and then examines the
	 * board.
	 */
	public void notifyTurn() {
		// System.out.println(playerType + " turn.");

		Move m = this.evaluateMove();

		System.out.println("MOVE IS "+m.toString());
		if (m instanceof WalkMove) {
			gameClient.tryMove(((WalkMove) m).getSource(),
					((WalkMove) m).getTarget());
		}
		if (m instanceof WallMove) {
			gameClient.tryMove(((WallMove) m).a1(), ((WallMove) m).a2(),
					((WallMove) m).b1(), ((WallMove) m).b2());
		}
	}

	private Move evaluateMove() {
		Move res = null;
		int tmpTurn = board.getTurn();
		int[] loc = board.getPlayerLocation(tmpTurn);
		boolean isWalkMove = Math.random() > 0.2;
		if (board.getPlayerWalls(tmpTurn) == 0) {
			isWalkMove = true;
		}
		if (isWalkMove) {
			TreeSet<int[]> legalMoves = board.getLegalMoves(loc);
			int ind = (int) ((double) Math.random() * (double) legalMoves
					.size());
			int[] tmpCurrent = legalMoves.first(); // Temporary init value
			while (ind > 0) {
				tmpCurrent = (int[]) legalMoves.first();
				legalMoves.remove(tmpCurrent);
				ind--;
			}
			WalkMove current = new WalkMove(loc, tmpCurrent);
			res = current;
			//board.makeMove(current);
		} else {
			ArrayList<WallMove> walls = board.getAllBlockingWalls(loc, tmpTurn);
			if (walls.size() == 0)
				return null;
			int ind = (int) ((double) (Math.random() * (double) walls.size()));
			WallMove current = walls.get(ind);
			res = current;
			//board.makeMove(current);
		}
		System.out.println(board);
		return res;
	}

}